import React, { useState, useRef, useEffect } from "react";
import {
  View,
  ScrollView,
  Image,
  StyleSheet,
  Dimensions,
  TouchableOpacity,
  NativeScrollEvent,
  NativeSyntheticEvent,
} from "react-native";
import { Colors } from "@/constants/Colors";

const { width: SCREEN_WIDTH } = Dimensions.get("window");
const ITEM_WIDTH = SCREEN_WIDTH - 20; // 考虑边距

interface CarouselProps {
  images: string[];
  autoPlay?: boolean;
  interval?: number;
  height?: number;
  showIndicator?: boolean;
  borderRadius?: number;
}

export const Carousel: React.FC<CarouselProps> = ({
  images,
  autoPlay = true,
  interval = 3000,
  height = 200,
  showIndicator = true,
  borderRadius = 8,
}) => {
  // 创建循环数组：在原数组前后各添加一张图片
  const extendedImages = [images[images.length - 1], ...images, images[0]];
  const [activeIndex, setActiveIndex] = useState(1); // 从真实的第一张图片开始
  const scrollViewRef = useRef<ScrollView>(null);
  const [isScrolling, setIsScrolling] = useState(false);

  // 初始化滚动到第一张真实图片
  useEffect(() => {
    setTimeout(() => {
      scrollViewRef.current?.scrollTo({
        x: ITEM_WIDTH,
        animated: false,
      });
    }, 100);
  }, []);

  // 自动播放
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (autoPlay && !isScrolling) {
      timer = setInterval(() => {
        const nextIndex = activeIndex + 1;
        scrollToIndex(nextIndex);
      }, interval);
    }
    return () => timer && clearInterval(timer);
  }, [activeIndex, autoPlay, isScrolling]);

  // 滚动到指定索引
  const scrollToIndex = (index: number, animated = true) => {
    scrollViewRef.current?.scrollTo({
      x: index * ITEM_WIDTH,
      animated,
    });
  };

  // 处理滚动结束事件
  const handleScrollEnd = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
    const contentOffset = event.nativeEvent.contentOffset;
    const index = Math.round(contentOffset.x / ITEM_WIDTH);

    // 处理循环逻辑
    if (index === 0) {
      // 滚动到最后一张真实图片
      setActiveIndex(images.length);
      scrollToIndex(images.length, false);
    } else if (index === extendedImages.length - 1) {
      // 滚动到第一张真实图片
      setActiveIndex(1);
      scrollToIndex(1, false);
    } else {
      setActiveIndex(index);
    }

    setIsScrolling(false);
  };

  // 处理滚动开始
  const handleScrollBegin = () => {
    setIsScrolling(true);
  };

  // 获取实际显示的指示器索引
  const getIndicatorIndex = () => {
    if (activeIndex === 0) return images.length - 1;
    if (activeIndex === extendedImages.length - 1) return 0;
    return activeIndex - 1;
  };

  return (
    <View style={[styles.container, { height, borderRadius }]}>
      <ScrollView
        ref={scrollViewRef}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        onMomentumScrollEnd={handleScrollEnd}
        onScrollBeginDrag={handleScrollBegin}
        style={[styles.scrollView, { borderRadius }]}
      >
        {extendedImages.map((image, index) => (
          <TouchableOpacity
            key={index}
            activeOpacity={0.9}
            style={[styles.imageContainer, { width: ITEM_WIDTH }]}
          >
            <Image
              source={{ uri: image }}
              style={[
                styles.image,
                { width: ITEM_WIDTH, height, borderRadius },
              ]}
              resizeMode="cover"
            />
          </TouchableOpacity>
        ))}
      </ScrollView>

      {showIndicator && (
        <View style={styles.pagination}>
          {images.map((_, index) => (
            <View
              key={index}
              style={[
                styles.paginationDot,
                index === getIndicatorIndex() && styles.paginationDotActive,
              ]}
            />
          ))}
        </View>
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginHorizontal: 10,
    marginVertical: 10,
    overflow: "hidden",
  },
  scrollView: {
    overflow: "hidden",
  },
  imageContainer: {
    overflow: "hidden",
  },
  image: {
    flex: 1,
  },
  pagination: {
    flexDirection: "row",
    position: "absolute",
    bottom: 10,
    alignSelf: "center",
  },
  paginationDot: {
    width: 6,
    height: 6,
    borderRadius: 3,
    marginHorizontal: 3,
    backgroundColor: "rgba(255, 255, 255, 0.4)",
  },
  paginationDotActive: {
    backgroundColor: Colors.primary,
    width: 12,
  },
});
